package com.kymatrix.mpo.plus.bpm.server.service.impl;

import com.kymatrix.mpo.plus.bpm.server.dao.definition.BpmProcessExpressionMapper;
import com.kymatrix.mpo.plus.bpm.server.model.entity.definition.BpmProcessExpressionEntity;
import com.kymatrix.mpo.plus.bpm.server.model.form.expression.PageQueryBpmProcessExpressionPageReq;
import com.kymatrix.mpo.plus.bpm.server.model.form.expression.SaveBpmProcessExpressionReq;
import com.kymatrix.mpo.plus.bpm.server.model.form.expression.UpdateBpmProcessExpressionReq;
import com.kymatrix.mpo.plus.bpm.server.service.BpmProcessExpressionService;
import com.kymatrix.mpo.plus.common.business.common.PageResp;
import com.kymatrix.mpo.plus.common.exception.BusinessException;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static com.kymatrix.mpo.plus.bpm.server.model.enums.ErrorCodeConstants.PROCESS_EXPRESSION_NOT_EXISTS;

/**
 * BPM 流程表达式 Service 实现类
 */
@Service
@Validated
public class BpmProcessExpressionServiceImpl implements BpmProcessExpressionService {

    @Resource
    private BpmProcessExpressionMapper processExpressionMapper;

    @Override
    public String createProcessExpression(SaveBpmProcessExpressionReq req) {
        BpmProcessExpressionEntity entity = new BpmProcessExpressionEntity();
        entity.setName(req.getName());
        entity.setStatus(req.getStatus());
        entity.setExpression(req.getExpression());
        processExpressionMapper.insert(entity);
        return entity.getId();
    }

    @Override
    public void updateProcessExpression(UpdateBpmProcessExpressionReq req) {
        // 校验存在
        validateProcessExpressionExists(req.getId());
        // 更新
        BpmProcessExpressionEntity entity = this.processExpressionMapper.selectById(req.getId());
        entity.setName(req.getName());
        entity.setStatus(req.getStatus());
        entity.setExpression(req.getExpression());
        processExpressionMapper.updateById(entity);
    }

    @Override
    public void deleteProcessExpression(String id) {
        // 删除
        processExpressionMapper.deleteById(id);
    }

    private void validateProcessExpressionExists(Long id) {
        if (processExpressionMapper.selectById(id) == null) {
            throw new BusinessException(PROCESS_EXPRESSION_NOT_EXISTS);
        }
    }

    @Override
    public BpmProcessExpressionEntity getProcessExpression(String id) {
        return processExpressionMapper.selectById(id);
    }

    @Override
    public PageResp<BpmProcessExpressionEntity> getProcessExpressionPage(PageQueryBpmProcessExpressionPageReq req) {
        return processExpressionMapper.selectPage(req);
    }

}
